<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="120px"
        class="demo-formData"
      >
        <el-row>
          <el-col :span="24">
            <el-row>
              <div>
                <el-form-item
                  prop="name"
                  label="考核名称："
                  class="row-padding-bottom"
                >
                  <el-input
                    type="text"
                    v-model.trim="formData.name"
                    :disabled="disabled"
                    placeholder="请输入"
                    class="proInputWidth mWidth"
                    clearable
                  ></el-input>
                </el-form-item>
              </div>
              <div>
                <el-form-item
                  prop="assessAreaStr"
                  label="考核对象："
                  class="row-padding-bottom"
                >
                  <el-input
                    type="text"
                    v-model="formData.assessAreaStr"
                    :disabled="disabled"
                    placeholder="请选择"
                    class="proInputWidth xlWidth"
                    @focus="showCheckObjectDialog = true"
                    clearable
                  ></el-input>
                </el-form-item>
              </div>
            </el-row>
            <el-row>
              <div :span="12">
                <el-form-item
                  prop="periodType"
                  label="考核周期："
                  class="row-padding-bottom"
                >
                  <el-radio-group
                    v-model="formData.periodType"
                    :disabled="disabled"
                    size="mini"
                    @change="getCircle"
                  >
                    <el-radio label="01" size="mini">月</el-radio>
                    <el-radio label="03" size="mini">季度</el-radio>
                    <el-radio label="05" size="mini">年</el-radio>
                    <el-radio label="07" size="mini">自定义</el-radio>
                  </el-radio-group>
                  <el-row>
                    <el-col :span="24" v-show="showMonthTime">
                      <el-form-item
                        prop="month"
                        label=""
                        class="row-padding-bottom"
                      >
                        <el-date-picker
                          v-model="formData.month"
                          :editable="false"
                          :disabled="disabled"
                          type="month"
                          value-format="yyyy-MM"
                          placeholder="选择月"
                          class="proInputWidth sWidth"
                          clearable
                        ></el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24" v-show="showQuarterDate">
                      <el-row>
                        <el-col
                          style="
                            margin-right: 14px;
                            display: inline-block;
                            width: 128px;
                          "
                        >
                          <el-form-item class="row-padding-bottom">
                            <!--         <span @click="showDoubleMonth"><el-input v-model="formData.quater"  :editable="false"  :disabled="disabled" placeholder="选择季度" clearable></el-input></span>-->
                            <el-select
                              v-model="quaterYear"
                              filterable
                              placeholder="请选择年"
                              class="xsWidth"
                              clearable
                            >
                              <el-option
                                v-for="item in yearList"
                                :key="item.id"
                                :label="item.text"
                                :value="item.id"
                              ></el-option>
                            </el-select> </el-form-item
                        ></el-col>
                        <el-col
                          style="
                            display: inline-block;
                            width: calc(100% - 150px);
                          "
                          ><el-form-item
                            prop="quater"
                            class="row-padding-bottom"
                          >
                            <el-select
                              v-model="formData.num"
                              filterable
                              placeholder="请选择季"
                              class="sWidth"
                              clearable
                            >
                              <el-option
                                v-for="item in monList"
                                :key="item.id"
                                :label="item.text"
                                :value="item.id"
                              ></el-option>
                            </el-select> </el-form-item
                        ></el-col>
                      </el-row>
                      <div class="showTimeBox" v-show="showQuaterTime">
                        <p>
                          <button
                            type="button"
                            aria-label="前一年"
                            class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-d-arrow-left"
                            @click="prev"
                          ></button>
                          <span role="button" class="span-year"
                            >{{ year }}年</span
                          >
                          <button
                            type="button"
                            aria-label="后一年"
                            @click="next"
                            class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-d-arrow-right"
                          ></button>
                        </p>
                        <p v-for="(item, index) in fullMonth" :key="index">
                          <span
                            class="selectMonth"
                            @click="selectQuarter(index)"
                            >{{ item }}</span
                          >
                        </p>
                      </div>
                    </el-col>
                    <el-col :span="24" v-show="showYearTime">
                      <el-form-item
                        prop="year"
                        label=""
                        class="row-padding-bottom"
                      >
                        <el-date-picker
                          v-model="formData.year"
                          :editable="false"
                          :disabled="disabled"
                          type="year"
                          value-format="yyyy"
                          placeholder="选择年"
                          class="proInputWidth sWidth"
                          clearable
                        ></el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24" v-show="showDefinedTime">
                      <el-form-item
                        prop="defined"
                        label=""
                        class="row-padding-bottom"
                      >
                        <el-date-picker
                          v-model="formData.defined"
                          :disabled="disabled"
                          type="monthrange"
                          value-format="yyyy-MM"
                          range-separator="至"
                          start-placeholder="开始月份"
                          end-placeholder="结束月份"
                          class="proInputWidth sWidth"
                          clearable
                        >
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form-item>
              </div>
              <div>
                <el-form-item
                  prop="illustration"
                  label="考核说明："
                  class="row-padding-bottom"
                >
                  <el-input
                    v-model.trim="formData.illustration"
                    rows="5"
                    style="width: calc(88% - 14px)"
                    :disabled="disabled"
                    type="textarea"
                    placeholder="请输入考核说明"
                    clearable
                    class="proInputWidth"
                  ></el-input>
                </el-form-item>
              </div>
            </el-row>
            <el-row>
              <div>
                <el-form-item
                  prop="assessTypeId"
                  label="评价方式："
                  class="row-padding-bottom"
                >
                  <el-select
                    v-model="formData.assessTypeId"
                    :disabled="disabled"
                    class="proInputWidth mWidth"
                    clearable
                  >
                    <el-option
                      label="地区自评+上级地区评定"
                      value="1"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div>
                <el-form-item
                  prop="expireDate"
                  label="到期时间："
                  class="row-padding-bottom"
                >
                  <el-date-picker
                    v-model="formData.expireDate"
                    align="right"
                    value-format="yyyy-MM-dd"
                    type="date"
                    placeholder="请选择"
                    class="proInputWidth sWidth"
                    :picker-options="pickerOptions"
                    clearable
                  ></el-date-picker>
                  <p :style="{ color: '#999' }">时间到期后,不能再提交自评</p>
                </el-form-item>
              </div>
            </el-row>
            <el-row>
              <div>
                <el-form-item
                  prop="templateId"
                  label="考核模板："
                  class="row-padding-bottom"
                >
                  <el-select
                    v-model="formData.templateId"
                    :disabled="disabled"
                    placeholder="请选择"
                    class="proInputWidth mWidth"
                    clearable
                  >
                    <el-option
                      v-for="item in options"
                      :label="item.name + '(总分:' + item.score + ')'"
                      :key="item.id"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-row>
          </el-col>
        </el-row>

        <div class="submitBox">
          <el-button
            type="primary"
            class="commonBut saveBtn"
            @click.native="saveForm"
            :disabled="btnChangeEnable"
            :loading="isSaveLoading"
            >{{ titleText }}</el-button
          >
          <el-button class="commonBut" @click="goBack">取消</el-button>
        </div>
      </el-form>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      width="40%"
      title="选择考核对象"
      :visible.sync="showCheckObjectDialog"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <span>
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          >全选</el-checkbox
        >
        <div style="margin: 15px 0"></div>
        <el-checkbox-group
          v-model="checkedCities"
          @change="handleCheckedCitiesChange"
        >
          <el-checkbox v-for="city in citiesName" :label="city" :key="city">{{
            city
          }}</el-checkbox>
        </el-checkbox-group>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showCheckObjectDialog = false" class="cancel"
          >取 消</el-button
        >
        <el-button type="primary" @click="getCheckObjectVal" class="save"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import common from '../../kits/common'
const cityOptions = [
  '荆门市',
  '恩施市',
  '天门市',
  '黄冈市',
  '武汉市',
  '仙桃市',
  '宜昌市',
  '荆州市',
  '荆州市',
]
export default {
  name: 'createAffairs',
  data() {
    var checkDate = (rule, value, callback) => {
      if (this.formData.periodType === '01') {
        //月
        var month = this.formData.month
        if (!month) {
          return callback(new Error('请选择月'))
        } else {
          callback()
        }
      } else if (this.formData.periodType === '03') {
        //季度
        var quater = this.formData.num
        if (!quater) {
          return callback(new Error('请选择季度'))
        } else {
          callback()
        }
      } else if (this.formData.periodType === '05') {
        //年
        var year = this.formData.year
        if (!year) {
          return callback(new Error('请选择年'))
        } else {
          callback()
        }
      } else if (this.formData.periodType === '07') {
        //自定义
        var defined = this.formData.defined
        if (!defined.length) {
          return callback(new Error('请选择自定义周期'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      id: '',
      titleText: '创建考核',
      back: true,
      btnChangeEnable: false,
      showMonthTime: true, //月
      showYearTime: false, //年
      showQuaterTime: false, //季度
      showQuarterDate: false,
      showDefinedTime: false, //自定义
      showCheckObjectDialog: false,

      props: {
        multiple: true,
        expandTrigger: 'hover',
        emitPath: false,
      },
      quaterYear: 2019,
      quaterMon: '',
      yearList: [],
      monList: [
        { id: 1, text: '第一季度(1-3月)' },
        { id: 2, text: '第二季度(4-6月)' },
        { id: 3, text: '第三季度(7-9月)' },
        { id: 4, text: '第四季度(10-12月)' },
      ],
      checkAll: false,
      checkedCities: [],
      cities: [],
      citiesName: [],
      isIndeterminate: true,
      options: [],
      isSaveLoading: false, // 保存loading
      disabled: false,
      formData: {
        name: '',
        assessArea: '',
        assessAreaStr: '',
        periodType: '01',
        illustration: '',
        assessTypeId: '1',
        assessTypeName: '地区自评+上级评定',
        expireDate: '',
        startDate: '',
        endDate: '',
        templateId: '',
        month: '',
        year: '',
        quater: '',
        num: '',
        defined: [],
      },

      //时期选择器
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        },
      },
      dataSize: '',
      chosesData: '',
      year: new Date().getFullYear(),
      fullMonth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      valueOrmatTwo: '',
      formRules: {
        name: [
          { required: true, message: '考核名称不能为空', trigger: 'change' },
          { min: 1, max: 32, message: '考核名称不超过32字', trigger: 'blur' },
        ],
        assessAreaStr: [
          { required: true, message: '考核对象不能为空', trigger: 'change' },
        ],
        periodType: [
          { required: true, message: '考核周期不能为空', trigger: 'change' },
        ],
        month: [{ required: true, validator: checkDate, trigger: 'blur' }],
        year: [{ required: true, validator: checkDate, trigger: 'blur' }],
        quater: [{ required: true, validator: checkDate, trigger: 'blur' }],
        defined: [{ required: true, validator: checkDate, trigger: 'blur' }],
        illustration: [
          { required: true, message: '考核说明不能为空', trigger: 'change' },
          { min: 1, max: 128, message: '考核说明不超过128字', trigger: 'blur' },
        ],
        assessTypeId: [
          { required: true, message: '评价方式不能为空', trigger: 'change' },
        ],
        templateId: [
          { required: true, message: '考核模板不能为空', trigger: 'change' },
        ],
      },
    }
  },
  created() {
    this.id = this.$route.query.id
    if (this.id) {
      this.titleText = '修改考核'
    }
    this.yearList = []
    for (var i = 2019; i < 2101; i++) {
      this.yearList.push({ id: i, text: i + '年' })
    }
    //取区域
    this.axios({
      method: 'post',
      url: 'api-gov/assess/expand/arealist',
    })
      .then((response) => {
        if (!response.data.hasError) {
          var j = 0
          var len = response.data.result.length
          for (j = 0; j < len; j++) {
            this.cities.push(response.data.result[j].id)
            this.citiesName.push(response.data.result[j].areaName)
          }
          this.getById()
        } else {
          this.$message({
            type: 'error',
            message: response.data.errorMsg,
          })
        }
      })
      .catch((error) => {})

    //取模板
    this.axios({
      method: 'post',
      url: 'api-gov/assesspublish/expand/templateList',
    })
      .then((response) => {
        if (!response.data.hasError) {
          this.options = response.data.result
        } else {
          this.$message({
            type: 'error',
            message: response.data.errorMsg,
          })
        }
      })
      .catch((error) => {})
  },
  methods: {
    getById() {
      if (this.id) {
        this.axios({
          method: 'post',
          url: 'api-gov/assesspublish/expand/assesspublishdetail',
          data: { id: this.id },
        })
          .then((response) => {
            if (!response.data.hasError) {
              if (response.data.result.publishStatus !== 0) {
                this.disabled = true
              }
              for (var prop in response.data.result) {
                if (this.formData.hasOwnProperty(prop)) {
                  this.formData[prop] = response.data.result[prop]
                }
              }
              this.formData.month = response.data.result.startDate
              this.getCircle(this.formData.periodType)
              var arr = response.data.result.assessArea[0].split(',')
              var j = 0
              var len = arr.length //返回的是id值
              var names = []
              for (j = 0; j < len; j++) {
                names.push(this.citiesName[this.cities.indexOf(arr[j])])
                this.checkedCities.push(
                  this.citiesName[this.cities.indexOf(arr[j])]
                )
              }
              this.formData.assessAreaStr = names.join(',')

              if (this.formData.periodType === '01') {
                //月
                this.year = new Date().getFullYear()
                this.formData.month = response.data.result.startDate
              }
              if (this.formData.periodType === '03') {
                //季度
                //this.year = new Date(response.data.result.startDate).getFullYear();
                this.quaterYear = new Date(
                  response.data.result.startDate
                ).getFullYear()
                var month = response.data.result.startDate.substring(5)
                var num = 4
                if (month === '01' || month === '02' || month === '03') {
                  num = 1
                }
                if (month === '04' || month === '05' || month === '06') {
                  num = 2
                }
                if (month === '07' || month === '08' || month === '09') {
                  num = 3
                }
                this.formData.num = num
              }
              if (this.formData.periodType === '05') {
                //年
                this.year = new Date(
                  response.data.result.startDate
                ).getFullYear()
                this.formData.year = response.data.result.startDate
              }
              if (this.formData.periodType === '07') {
                //自定义
                this.formData.defined.push(response.data.result.startDate)
                this.formData.defined.push(response.data.result.endDate)
              }
            } else {
              this.$message({
                type: 'error',
                message: response.data.errorMsg,
              })
            }
          })
          .catch((error) => {})
      }
    },
    getCheckObjectVal() {
      this.showCheckObjectDialog = false
      //checkedCities存的是名称，要取出id
      var j = 0
      var len = this.checkedCities.length
      var ids = []
      for (j = 0; j < len; j++) {
        ids.push(this.cities[this.citiesName.indexOf(this.checkedCities[j])])
      }
      this.formData.assessAreaStr = this.checkedCities.join(',')
      this.formData.assessArea = ids.join(',')
    },

    handleCheckAllChange(val) {
      this.checkedCities = val ? this.citiesName : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.citiesName.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length
    },
    //周期选择
    getCircle(label) {
      if (label == '01') {
        this.showMonthTime = true
        this.showYearTime = false
        this.showQuarterDate = false
        this.showDefinedTime = false
      } else if (label == '03') {
        this.showMonthTime = false
        this.showYearTime = false
        this.showQuarterDate = true
        this.showDefinedTime = false
      } else if (label == '05') {
        this.showMonthTime = false
        this.showYearTime = true
        this.showQuarterDate = false
        this.showDefinedTime = false
      } else if (label == '07') {
        this.showMonthTime = false
        this.showYearTime = false
        this.showQuarterDate = false
        this.showDefinedTime = true
      }
    },
    showDoubleMonth() {
      this.showQuaterTime = true
    },
    prev() {
      this.year = this.year * 1 - 1
    },
    next() {
      this.year = this.year * 1 + 1
    },
    selectQuarter(index) {
      if (
        parseInt(index) == 0 ||
        parseInt(index) == 1 ||
        parseInt(index) == 2
      ) {
        this.formData.quater = this.year + '-' + '第1季度(1-3月)'
        this.formData.num = 1
        this.showQuaterTime = false
      } else if (
        parseInt(index) == 3 ||
        parseInt(index) == 4 ||
        parseInt(index) == 5
      ) {
        this.formData.quater = this.year + '-' + '第2季度(4-6月)'
        this.formData.num = 2
        this.showQuaterTime = false
      } else if (
        parseInt(index) == 6 ||
        parseInt(index) == 7 ||
        parseInt(index) == 8
      ) {
        this.formData.quater = this.year + '-' + '第3季度(7-9月)'
        this.formData.num = 3
        this.showQuaterTime = false
      } else {
        this.formData.quater = this.year + '-' + '第4季度(10-12月)'
        this.formData.num = 4
        this.showQuaterTime = false
      }
    },
    saveForm() {
      this.$refs.formData.validate((valid) => {
        if (this.formData.periodType === '01') {
          //月
          this.formData.startDate = this.formData.month
          this.formData.endDate = this.formData.month
        }
        if (this.formData.periodType === '03') {
          //季度
          if (this.formData.num === 1) {
            this.formData.startDate = this.quaterYear + '-01'
            this.formData.endDate = this.quaterYear + '-03'
          }
          if (this.formData.num === 2) {
            this.formData.startDate = this.quaterYear + '-04'
            this.formData.endDate = this.quaterYear + '-06'
          }
          if (this.formData.num === 3) {
            this.formData.startDate = this.quaterYear + '-07'
            this.formData.endDate = this.quaterYear + '-09'
          }
          if (this.formData.num === 4) {
            this.formData.startDate = this.quaterYear + '-10'
            this.formData.endDate = this.quaterYear + '-12'
          }
        }
        if (this.formData.periodType === '05') {
          //年
          this.formData.startDate = this.formData.year.substr(0, 4) + '-01'
          this.formData.endDate = this.formData.year.substr(0, 4) + '-12'
        }
        if (this.formData.periodType === '07') {
          //自定义
          this.formData.startDate = this.formData.defined[0]
          this.formData.endDate = this.formData.defined[1]
        }
        if (valid) {
          this.btnChangeEnable = true
          var txt = '创建成功'
          var url = 'api-gov/assesspublish/expand/createassesspublish'
          var data = {
            assessArea: this.formData.assessArea,
            periodType: this.formData.periodType,
            startDate: this.formData.startDate,
            endDate: this.formData.endDate,
            expireDate: this.formData.expireDate,
            illustration: this.formData.illustration,
            name: this.formData.name,
            templateId: this.formData.templateId,
            assessTypeId: this.formData.assessTypeId,
            assessTypeName: this.formData.assessTypeName,
          }
          if (this.id) {
            txt = '修改成功'
            url = 'api-gov/assesspublish/expand/updateassess'
            data.id = this.id
          }
          this.axios({
            method: 'post',
            url: url,
            data: data,
          })
            .then((response) => {
              if (!response.data.hasError) {
                this.$message({
                  type: 'success',
                  message: txt,
                })

                this.$router.push({ name: 'checkAffairsList' })
                this.$store.commit('CHANGE_SLIDER_NAME', {
                  oldUrl: '/home/checkAffairs/checkAffairsList',
                  newUrl: this.$router.currentRoute.fullPath,
                })
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.errorMsg,
                })
                this.btnChangeEnable = false
              }
            })
            .catch((error) => {})
        } else {
          return false
        }
      })
    },
    goBack() {
      this.$refs['formData'].resetFields()
      this.$router.push('/home/checkAffairs/checkAffairsList')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/checkAffairs/checkAffairsList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>
<style scoped lang="less">
.topTitle {
  height: 67px;
  background-color: #e4ebf1;
  padding-left: 24px;
  font: bold 18px/67px Microsoft YaHei;
}
.container {
  .mainCon {
    height: calc(100% - 67px);
    overflow-y: auto;
    padding: 40px;
    .labelStyMin {
      padding-left: 0px !important;
      min-width: 130px;
    }
    .labelStyMax {
      padding-left: 0px !important;
      margin-left: 5px;
      min-width: 155px;
    }
    .submitBox {
      margin-top: 20px;
      margin-left: 120px;
      // text-align: center;
    }
  }
}
form.el-form.demo-formData {
  width: 100%;
  display: inline-block;
  text-align: left;
  .proInputWidth {
    width: 70%;
  }
}
.saveBtn {
  background-color: #009588;
  border-color: #009588;
  color: #fff;
}

/*时间选择器样式*/
.navBar input {
  width: 215px;
  height: 38px;
  display: inline-block;
}
.showTimeBox {
  width: 320px;
  margin-top: 5px;
  position: absolute;
  z-index: 2;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background: #fff;
  padding: 20px;
}
.showTimeBox p:nth-child(1) {
  width: 100%;
  height: 40px;
  border-bottom: 1px solid #f5f5f5;
}
.showTimeBox p:nth-child(2) {
  box-sizing: border-box;
}
.selectMonth {
  display: inline-block;
  width: 78px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.selectMonth:hover {
  color: #409eff;
}
.span-year {
  width: 90%;
  margin: 0 auto;
  display: inline-block;
  text-align: center;
  line-height: 40px;
}
/deep/ .el-checkbox {
  width: 18%;
}
</style>
